package com.seven.mybatis.controller.login;

import com.seven.mybatis.bean.Smsinfo;
import com.seven.mybatis.bean.User;
import com.seven.mybatis.commons.HttpResult;
import com.seven.mybatis.commons.encryption.PasswordEncryptor;
import com.seven.mybatis.mapper.SmsDao;
import com.seven.mybatis.mapper.UserMapper;
import com.seven.mybatis.util.BCMessageUtil;
import com.seven.mybatis.util.BCUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/userAction")
@RestController
public class UserActionController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SmsDao smsdao;

    @Autowired
    UserMapper mapper;

    //还差一个东西，我怎么知道DB插入成功还是失败呢??

    /** 注册 */
    @PostMapping(value = "/register")
    public HttpResult<?> createUser(HttpServletRequest request,
                                 @RequestParam("password") String password,
                                 @RequestParam("smsCode") String smsCode,
                                 @RequestParam("type") String type,
                                 @RequestParam("phone") String phone) {

        //参数不能为空
        if (BCUtil.bc_isEmptyString(password) || BCUtil.bc_isEmptyString(phone)) {

            return HttpResult.createParamErrorResult();
        }

        //参数检查不合格
        if (phone.length() != 11) {

            return HttpResult.createMessageResult("手机号码错误");
        }

        //查询user
        User oldUser = mapper.bc_queryUserByPhoneNumber(phone);

        if (oldUser != null){

            return HttpResult.createParamErrorResult("该用户已经注册!");
        }

        String oldCode = smsdao.bc_querySMSByPhoneNumber(phone,type);

        logger.info("=====查询验证码======" + oldCode);

        if (!oldCode.equals(smsCode)) {

            return HttpResult.createParamErrorResult("验证码错误");
        }

        //所有的通过后，数据库里插入user

        String token = BCUtil.getToken();
        User freshUser = new User();
        freshUser.setRegisterdate(new Date());
        freshUser.setPhone(phone);
        freshUser.setToken(token);

        //密码处理logic
        String salt = UUID.randomUUID().toString();
        PasswordEncryptor encrypt = new PasswordEncryptor(salt, "sha-256");
        String encodedPassword = encrypt.encode(password);

        freshUser.setSalt(salt);
        freshUser.setPassword(encodedPassword);

        //插入DB
        mapper.bc_createUser(freshUser);

        Integer id = freshUser.getUserId();

        Map result = new HashMap();
        result.put("token", token);
        result.put("id", id);

        return HttpResult.createSuccessResult(result);
    }


    /** 登录 */
    @PostMapping("/login")
    public HttpResult<?> loginUser(HttpServletRequest request,
                                    @RequestParam("password") String password,
                                    @RequestParam("phone") String phone) {

        //参数不能为空
        if (BCUtil.bc_isEmptyString(password) || BCUtil.bc_isEmptyString(phone)) {

            return HttpResult.createParamErrorResult();
        }

        //参数检查不合格
        if (phone.length() != 11) {

            return HttpResult.createMessageResult("手机号码错误");
        }

        //查询user
        User oldUser = mapper.bc_queryUserByPhoneNumber(phone);

        if (BCUtil.bc_isEmptyObject(oldUser)){

            return HttpResult.createExceptionErrorResult("用户不存在");
        }

        //比对密码
        String salt = oldUser.getSalt();

        PasswordEncryptor encryptor = new PasswordEncryptor(salt, "sha-256");
        String encodedPassword = encryptor.encode(password);

        if (!encodedPassword.equals(oldUser.getPassword()) ) {

            return HttpResult.createExceptionErrorResult("密码错误");
        }

        User user = mapper.bc_queryUserByPhoneNumber(phone);

        Map result = new HashMap();
        result.put("token", user.getToken());
        result.put("id", user.getUserId());

        return HttpResult.createSuccessResult(result);
    }


    /** 重设密码 */
    @PostMapping(value = "/resetPassword")
    public HttpResult<?> resetPassword(HttpServletRequest request,
                                    @RequestParam("password") String password,
                                    @RequestParam("smsCode") String smsCode,
                                    @RequestParam("phone") String phone) {

        //参数不能为空
        if (BCUtil.bc_isEmptyString(password) || BCUtil.bc_isEmptyString(phone)) {

            return HttpResult.createParamErrorResult();
        }

        //参数检查不合格
        if (phone.length() != 11) {

            return HttpResult.createMessageResult("手机号码错误");
        }

        //查询user
        User oldUser = mapper.bc_queryUserByPhoneNumber(phone);

        if (oldUser == null){

            return HttpResult.createParamErrorResult("请先注册!");
        }


        String oldCode = smsdao.bc_querySMSByPhoneNumber(phone,"2");


        if (!oldCode.equals(smsCode)) {

            return HttpResult.createParamErrorResult("验证码错误");
        }

        //密码处理logic
        String salt = oldUser.getSalt();
        PasswordEncryptor encrypt = new PasswordEncryptor(salt, "sha-256");
        String encodedPassword = encrypt.encode(password);

        //所有的通过后，数据库更新密码
        mapper.bc_resetPasswordByPhoneNumber(phone, encodedPassword);


        return HttpResult.createSuccessResult();
    }

    /** 发送验证码 */
    @PostMapping("/sendSMS")
    public HttpResult<?> sendVerificationCode(HttpServletRequest request,
                                   @RequestParam("type") String type,
                                   @RequestParam("phone") String phone) {


        //参数不能为空
        if (BCUtil.bc_isEmptyString(type) || BCUtil.bc_isEmptyString(phone)) {

            return HttpResult.createParamErrorResult();
        }

        //参数检查不合格
        if (phone.length() != 11) {

            return HttpResult.createMessageResult("手机号码错误");
        }

        //调用第三方发送code 并保存备用
        String code = BCMessageUtil.bc_sendMessageTo(phone);

        Smsinfo info = new Smsinfo();

        info.setCode(code);
        info.setPhone(phone);
        info.setType(type);

        smsdao.bc_createSMS(info);

        return HttpResult.createSuccessResult();
    }

}
